package com.mchat.friend.controller;

import com.mchat.exceptions.CommonException;
import com.mchat.friend.domain.dto.FriendRequestDTO;
import com.mchat.friend.domain.dto.FriendDescribeDTO;
import com.mchat.friend.domain.dto.FriendReplyDTO;
import com.mchat.friend.domain.vo.FriendRequestVO;
import com.mchat.friend.domain.vo.FriendVO;
import com.mchat.friend.service.IFriendService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static com.mchat.util.Utils.getUid;

@RestController
@RequestMapping("/friend")
@AllArgsConstructor
public class FriendController {
    private final IFriendService friendService;
    @PostMapping("/send-apply")
    public Mono<FriendRequestVO> apply(ServerWebExchange exchange, @RequestBody FriendRequestDTO dto){
        Long uid = getUid(exchange);
        dto.setSendId(uid);
        if (dto.getReceiverId()!=null)
            return friendService.apply(dto);
        return Mono.error(new CommonException("参数错误"));
    }

    @PutMapping("/reply")
    public Mono<Long>processApply(ServerWebExchange exchange, @RequestBody() FriendReplyDTO dto){
        Long uid = getUid(exchange);
        dto.setReceiverId(uid);
        if (dto.getSendId()!=null)
            return friendService.reply(dto);
        return Mono.error(new CommonException("参数错误"));
    }

    @GetMapping(value = "/friendApply",produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<FriendRequestVO> getApply(ServerWebExchange webExchange) {
        return friendService.getFriendApply(getUid(webExchange));
    }
    @PostMapping("/deleteFriend")
    public Mono<Long>deleteFriend(ServerWebExchange exchange,@RequestParam Long friendId){
        long uid=getUid(exchange);
        return friendService.deleteFriend(uid,friendId);
    }

    @PutMapping("/setFriend")
    public Mono<Long> setFriend(ServerWebExchange exchange,@RequestBody FriendDescribeDTO dto){
        dto.setUid(getUid(exchange));
        exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
        return friendService.setFriend(dto);
    }
    @GetMapping(value="/friend",produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<FriendVO>getFriend(ServerWebExchange exchange){
        return friendService.getFriend(getUid(exchange));
    }
}
